const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const bodyParser = require('body-parser');

// 状态码定义
const CODE = {
  SUCCESS: 0,
  PARAM_ERROR: 1001,
  NOT_FOUND: 1002,
  SERVER_ERROR: 500
};

/**
 * 记录操作日志
 * @param {object} params - 日志参数对象
 * @param {number} params.userId - 用户ID
 * @param {string} params.type - 操作类型（如：create, update, delete等）
 * @param {string} params.module - 操作模块（如：用户管理、项目管理等）
 * @param {string} params.details - 操作描述
 * @param {string} params.ipAddress - IP地址
 * @param {string} params.userAgent - 浏览器信息
 * 
 * @example
 * // 在其他模块中使用示例：
 * const { logOperation } = require('./routes/logs');
 * 
 * await logOperation({
 *   userId,
 *   type: 'create',
 *   module: '项目管理',
 *   details: '创建新项目：XXX',
 *   ipAddress: req.ip,
 *   userAgent: req.headers['user-agent']
 * });
 */
const logOperation = async (params) => {
  try {
    // 处理可能为 undefined 的参数
    await pool.execute(
      'INSERT INTO operation_logs (user_id, action, module, description, ip_address, user_agent, create_time) VALUES (?, ?, ?, ?, ?, ?, NOW())',
      [
        params.userId || null, 
        params.type || '', 
        params.module || '', 
        params.details || '', 
        params.ipAddress || '', 
        params.userAgent || ''
      ]
    );
  } catch (error) {
    console.error('记录日志错误:', error);
  }
};

// 获取日志列表
router.get('/list', async (req, res) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      userId,
      module,
      action,
      startDate,
      endDate
    } = req.query;

    let conditions = [];
    let params = [];

    // 构建查询条件
    if (userId) {
      conditions.push('user_id = ?');
      params.push(userId);
    }
    if (module) {
      conditions.push('module = ?');
      params.push(module);
    }
    if (action) {
      conditions.push('action = ?');
      params.push(action);
    }
    if (startDate && endDate) {
      conditions.push('create_time BETWEEN ? AND ?');
      params.push(startDate, endDate);
    }

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
    const offset = (page - 1) * pageSize;

    // 获取日志列表
    const [logs] = await pool.execute(
      `SELECT ol.*, u.username, u.real_name
       FROM operation_logs ol
       LEFT JOIN users u ON ol.user_id = u.id
       ${whereClause}
       ORDER BY ol.create_time DESC
       LIMIT ? OFFSET ?`,
      [...params, parseInt(pageSize), offset]
    );

    // 获取总数
    const [countResult] = await pool.execute(
      `SELECT COUNT(*) as total FROM operation_logs ol ${whereClause}`,
      params
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取日志列表成功',
      data: {
        total: countResult[0].total,
        list: logs,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    });
  } catch (error) {
    console.error('获取日志列表错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 获取日志详情
router.get('/details/:id', async (req, res) => {
  try {
    const { id } = req.params;

    const [logs] = await pool.execute(
      `SELECT ol.*, u.username, u.real_name
       FROM operation_logs ol
       LEFT JOIN users u ON ol.user_id = u.id
       WHERE ol.id = ?`,
      [id]
    );

    if (logs.length === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '日志不存在'
      });
    }

    res.json({
      code: CODE.SUCCESS,
      message: '获取日志详情成功',
      data: logs[0]
    });
  } catch (error) {
    console.error('获取日志详情错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 删除日志
router.delete('/delete/:id', async (req, res) => {
  try {
    const { id } = req.params;

    const [result] = await pool.execute(
      'DELETE FROM operation_logs WHERE id = ?',
      [id]
    );

    if (result.affectedRows === 0) {
      return res.json({
        code: CODE.NOT_FOUND,
        message: '日志不存在'
      });
    }

    // 记录操作日志
    await logOperation({
      userId: req.user.userId,
      type: 'delete',
      module: '日志管理',
      details: `删除日志：${id}`,
      ipAddress: req.ip,
      userAgent: req.headers['user-agent']
    });

    res.json({
      code: CODE.SUCCESS,
      message: '删除日志成功'
    });
  } catch (error) {
    console.error('删除日志错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 清空日志
router.delete('/clear', bodyParser.urlencoded({ extended: true }), async (req, res) => {
  try {
    const { 
      startDate = req.body['startDate'] || req.body['start_date'], 
      endDate = req.body['endDate'] || req.body['end_date'] 
    } = req.body;

    let sql = 'DELETE FROM operation_logs';
    let params = [];

    if (startDate && endDate) {
      sql += ' WHERE create_time BETWEEN ? AND ?';
      params.push(startDate, endDate);
    }

    const [result] = await pool.execute(sql, params);

    // 记录操作日志
    await logOperation({
      userId: req.user.userId,
      type: 'delete',
      module: '日志管理',
      details: `清空日志：${startDate || '全部'} - ${endDate || '全部'}`,
      ipAddress: req.ip,
      userAgent: req.headers['user-agent']
    });

    res.json({
      code: CODE.SUCCESS,
      message: '清空日志成功',
      data: {
        deletedCount: result.affectedRows
      }
    });
  } catch (error) {
    console.error('清空日志错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 获取日志action
router.get('/action', async (req, res) => {
  try {
    const [actionList] = await pool.execute(
      // mysql 75.7.23 mysql 1055错误，select 的字段必须在groupu中
      //'SELECT id,action,module from operation_logs GROUP BY action'
      `SELECT any_value(id) as id,action,any_value(module) as moudle from operation_logs GROUP BY action`
    );

    res.json({
      code: CODE.SUCCESS,
      message: '获取日志action成功',
      data: actionList
    });
  } catch (error) {
    console.error('获取日志action错误:', error);
    res.status(500).json({
      code: CODE.SERVER_ERROR,
      message: '服务器错误'
    });
  }
});

// 导出路由和日志记录函数
module.exports = router;
module.exports.logOperation = logOperation;
